// pages/citychoose/citychoose.js
const staticData = require("../../data/staticData");
Page({
  data: {
    showItems: {},
    citys: [],
    hotcitys: [],
    inputText: ""

  },
  onLoad: function (options) {
    this.getHotCities();
    let citys = this.getSortedAreaObj(staticData.cities || []);
    this.setData({
      citys,
      showItems: citys
    });
  },
  getSortedAreaObj(areas) {
    areas = areas.sort((a, b) => {
      if (a.letter > b.letter) {
        return 1
      }
      if (a.letter < b.letter) {
        return -1
      }
      return 0
    });
    return areas.reduce((obj, item) => {
      let key = item["letter"];
      if (obj[key]) {
        obj[key] = obj[key].concat(item);
        return obj;
      } else {
        obj[key] = [].concat(item);
        return obj;
      }
    }, {});
  },
  getHotCities(callback) {
    // let m = wx.cloud.callFunction({
    //   name: 'getHotCities'
    // }).then(res => {
    //   let hotcitys = res.result;
    //   this.setData({
    //     hotcitys
    //   });
    // });
    // console.log(m);
    let hotcitys = [{
      "letter": "C",
      "name": "承德市"
    }, {
      "letter": "C",
      "name": "沧州市"
    }, {
      "letter": "L",
      "name": "廊坊市"
    }, {
      "letter": "H",
      "name": "衡水市"
    }, {
      "letter": "T",
      "name": "太原市"
    }, {
      "letter": "D",
      "name": "大同市"
    }, {
      "letter": "Y",
      "name": "阳泉市"
    }, {
      "letter": "C",
      "name": "长治市"
    }];
    this.setData({
      hotcitys
    });
  },
  inputFilter(e) {
    let value = e.detail.value;
    if (!value)
      return;
    let showitems = {};
    for (const key in this.data.citys) {
      let citys = this.data.citys[key];
      let items = citys.map(c => {
        if (c.name.toLowerCase().includes(value.toLowerCase()))
          return c;
        else return null;
      });

      items = items.filter(c => c);
      if (items.length > 0)
        showitems[key] = items;
    }

    this.setData({
      showItems: showitems
    });
  },
  cancel() {
    this.setData({
      inputText: "",
      showItems: this.data.citys
    });
  },
  choose(e) {
    let dataset = ((e.currentTarget || {}).dataset) || {};
    let name = dataset.name || '';
    const pages = getCurrentPages();
    let len = pages.length;
    let indexPage = pages[len - 2]
    indexPage.search(name, () => {
      wx.navigateBack({});
    });
  }
})